package com.lagou.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.lagou.bean.OssResult;
import com.lagou.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
@Service
public class OssService {
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient  ossClient;
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{ ".jpg",
            ".jpeg",  ".png"};
    public OssResult upload(MultipartFile multipartFile){
        // 校验图片格式
        boolean  isLegal = false;
        for (String type:IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }
        OssResult ossResult = new OssResult();
        if (!isLegal){
            ossResult.setStatus("error");
            ossResult.setResponse("必须为 jpg、png 或者 jpeg类型");
            return  ossResult;
        }
        // 大小检查
        long size = multipartFile.getSize();
        if (size>5*1024*1024){
            ossResult.setResponse("必须小于5M");
            ossResult.setStatus("error");
            return  ossResult;
        }


        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            ossResult.setStatus("error");
            return  ossResult;
        }
        ossResult.setStatus("done");
        ossResult.setName(aliyunConfig.getUrlPrefix()+filePath);
        ossResult.setUid(filePath);
        return  ossResult;
    }
    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    public void download(String name, HttpServletResponse response){
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), name);
        try {
            downLoadFile(ossObject,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void downLoadFile(OSSObject ossObject, HttpServletResponse response) throws IOException {
        BufferedInputStream bis = null;
        OutputStream toClient = null;
        try {
            //*获取ossObject的流*
            bis = new BufferedInputStream(ossObject.getObjectContent(),512);

            //获取oss端文件的文件名，用作于下载文件的名称
            String[] arr = ossObject.getKey().split("/");
            String fileName = arr[arr.length - 1];

            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //处理文件名为中文的情况
            response.setHeader("Content-Disposition","attach;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));

            //*处理oss文件流传输*
            int number;
            byte[] buffer = new byte[512];
            while ((number = bis.read(buffer)) != -1){
                toClient.write(buffer,0,number);
            }
            toClient.flush();
            toClient.close();
        }finally {
            if(toClient != null){
                toClient.close();
            }
            if(bis != null){
                bis.close();
            }
        }
    }

    public OssResult delete(String name){
//        ossClient.deleteObject(bucketName, objectName);
        ossClient.deleteObject(aliyunConfig.getBucketName(), name);
        OssResult ossResult = new OssResult();

        ossResult.setStatus("done");
        return ossResult;

    }

}
